<?php

namespace App\Console\Commands\Craw;

use App\Tools\Curl;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class Fenbi extends Command
{
  /**
   * The name and signature of the console command.
   *
   * @var string
   */
  protected $signature = 'Fenbi {one?}';

  /**
   * The console command description.
   *
   * @var string
   */
  protected $description = 'Command description';

  /**
   * Execute the console command.
   */
  public function handle()
  {
    $one = $this->argument('one');

    // staticUrl 拿 JSON
    if ($one == 'step4') {
      $zhentis = DB::select('select * from fenbi_zhentis where `raw1` is null');
      foreach ($zhentis as $zhenti) {
        // dd($zhenti);
        $url = $zhenti['staticUrl'];
        $r = Curl::getFenbi($url);
        DB::update('update fenbi_zhentis set `raw1` = ? where id = ?', [$r, $zhenti['id']]);
        sleep(1);
        echo '完成' . $zhenti['id'] . "\n";
      }
    }

    // key 换 staticUrl
    if ($one == 'step3') {
      $zhentis = DB::select('select * from fenbi_zhentis where `staticUrl` is null');
      foreach ($zhentis as $zhenti) {
        // dd($zhenti);
        $url = 'https://tiku.fenbi.com/combine/exercise/getExercise?format=html&key=' . $zhenti['key'] . '&routecs=xingce&kav=121&av=121&hav=121&app=web';
        $r = Curl::getFenbi($url);
        $staticUrl = json_decode($r, true)['data']['staticUrl']['urls'][0];
        $staticUrl .= '&routecs=xingce&type=1&kav=121&av=121&hav=121&app=web';
        // dd($staticUrl);
        DB::update('update fenbi_zhentis set `staticUrl` = ? where id = ?', [$staticUrl, $zhenti['id']]);
        sleep(1);
        echo '完成' . $zhenti['id'] . "\n";
      }
    }

    // ID 换 key
    if ($one == 'step2') {
      $zhentis = DB::select('select * from fenbi_zhentis where `key` is null');
      foreach ($zhentis as $zhenti) {
        // dd($zhenti);
        $url = 'https://tiku.fenbi.com/api/xingce/exercises?app=web&kav=100&av=121&hav=100&version=3.0.0.0';
        $r = Curl::postFenbi($url, [
          'type' => 1,
          'exerciseTimeMode' => 2,
          'paperId' => $zhenti['id'],
        ]);
        $key = json_decode($r, true)['key'];
        DB::update('update fenbi_zhentis set `key` = ? where id = ?', [$key, $zhenti['id']]);
        sleep(1);
        echo '完成' . $zhenti['id'] . "\n";
      }
    }

    // 从JSON导入到数据库
    if ($one == 'step1') {
      $list = json_decode(file_get_contents(__DIR__ . '/list.json'), true);
      $dataForInsert = [];
      foreach ($list['list'] as $one) {
        $dataForInsert[] = [
          'id' => $one['id'],
          'name' => $one['name'],
          'raw' => json_encode($one, JSON_UNESCAPED_UNICODE),
        ];
      }
      DB::table('fenbi_zhentis')->insert($dataForInsert);
    }
  }
}
